<script>
import {
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  watch,
  onUnmounted,
} from "vue";
import TabCard from "../../../components/TabCard.vue";
import ConfigItem from "../../../components/ConfigItem.vue";
import ModuleCard from "../../../components/ModuleCard.vue";
import UserTable from "../../../components/UserTable.vue";
import InfoButton from "../../../components/InfoButton.vue";
import SaveButton from "../../../components/SaveButton.vue";
import ConfigInput from "../../../components/ConfigInput.vue";
import TimeZoneSelect from "../../../components/TimeZoneSelect.vue";
import {
  editConfigSystemBasic,
  editConfigSystemTime,
  getConfigList,
  resetConfig,
  restartSystem,
  getServerTime,
  setServerTime,
} from "@/api/configure.js";
import { useRoute } from "vue-router";
import { useUserStore } from "@/store/modules/user.js";

export default defineComponent({
  components: {
    InfoButton,
    TabCard,
    ConfigItem,
    ModuleCard,
    UserTable,
    SaveButton,
    ConfigInput,
    TimeZoneSelect,
  },
  setup() {
    const state = reactive({
      currentTab: -1,
      formData: {
        tab1: {
          deviceName: "",
          deviceNum: "",
          deviceCategory: "",
          deviceSn: "",
        },
        tab2: {
          timezone: "GMT_10M",
          serveAddress: "",
          ntpPort: "",
          timingInterval: "",
          deviceTime: "",
          setUpTime: "",
        },
      },
      isSyncTime: false,
      checkWay1: false,
      checkWay2: false,
      defaultIndexNum: 0,
      nowTimer: "",
      setTimer: "",
      isShow: false,
    });

    const route = useRoute();
    const store = useUserStore();

    watch(
      () => route.query,
      (a) => {
        if (a.index === "3") {
          state.defaultIndexNum = 3;
        }
      },
      {
        immediate: true,
      }
    );

    watch(
      () => store.count,
      (a) => {
        if (store.count === 1) {
          state.currentTab = 3;
        }
      },
      {
        immediate: true,
      }
    );
    watch(
      () => state.checkWay2,
      (a) => {
        if (a) {
          // const now = new Date();
          let time;
          getServerTime().then((res) => {
            if (res.code === 200) {
              time = new Date(res.data);
              state.formData.tab2.deviceTime = time.toLocaleString();

              let nowStamp = Date.parse(time);
              state.nowTimer = setInterval(() => {
                nowStamp = nowStamp + 1000;
                state.formData.tab2.deviceTime = new Date(
                  nowStamp
                ).toLocaleString();
              }, 1000);
            }
          });
        } else {
          clearInterval(state.nowTimer);
          clearInterval(state.setTimer);
          state.formData.tab2.deviceTime = "";
          state.formData.tab2.setUpTime = "";
        }
      },
      {
        immediate: true,
      }
    );

    onMounted(() => {
      getConfig();
    });

    onUnmounted(() => {
      clearInterval(state.nowTimer);
      clearInterval(state.setTimer);
    });

    //获取配置列表
    const getConfig = () => {
      getConfigList(0).then(
        (info) => {
          if (info.code === 200) {
            state.formData.tab1 = info.data.configSystemBasic;
            state.formData.tab2 = info.data.configSystemTime;
            state.formData.tab2.setUpTime = "";

            if (info.data.configSystemTime.optionTYpe === 0) {
              state.checkWay1 = true;
              state.checkWay2 = false;
            } else {
              state.checkWay2 = true;
              state.checkWay1 = false;
            }
          } else {
            ElMessage({
              message: info.message,
              type: "warning",
            });
          }
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };

    const handleTabCurrentChange = (e) => {
      state.currentTab = e;
    };

    //保存基本信息配置
    const saveBasic = () => {
      editConfigSystemBasic(state.formData.tab1).then(
        (info) => {
          if (info.code === 200) {
            ElMessage({
              message: "保存成功",
              type: "success",
              offset: 400,
            });
          } else {
            ElMessage({
              message: info.message,
              type: "warning",
            });
          }
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };
    //保存时间配置
    const saveTime = () => {
      let data;
      if (state.checkWay1 === state.checkWay2) {
        ElMessage({
          message: "请选择一种校准方式",
          type: "warning",
          offset: 400,
        });
        return;
      }
      if (state.checkWay1) {
        data = {
          ntpPort: state.formData.tab2.ntpPort,
          serveAddress: state.formData.tab2.serveAddress,
          timezone: state.formData.tab2.timezone,
          timingInterval: state.formData.tab2.timingInterval,
          optionTYpe: 0,
        };
      } else {
        data = {
          deviceTime: state.formData.tab2.deviceTime,
          timezone: state.formData.tab2.timezone,
          optionTYpe: 1,
          setUpTime: state.formData.tab2.setUpTime,
        };

        setServerTime(state.formData.tab2.setUpTime).then((res) => {
          if (res.code === 200 && res.status) {
            ElMessage({
              message: "修改成功",
              type: "success",
              offset: 400,
            });
            state.isShow = true;
          }
        });
      }

      editConfigSystemTime(data).then(
        (info) => {
          if (info.code === 200) {
            ElMessage({
              message: "保存成功",
              type: "success",
              offset: 400,
            });
          } else {
            ElMessage({
              message: info.message,
              type: "warning",
            });
          }
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };

    //选择不同的校准方式
    const changeWay = (type) => {
      if (!type) {
        if (state.checkWay2) {
          state.checkWay1 = true;
          state.checkWay2 = false;
          state.isSyncTime = false;
        }
      } else {
        if (state.checkWay1) {
          state.checkWay1 = false;
          state.checkWay2 = true;
        }
      }
    };

    //同步时间
    const changeNowTime = (e) => {
      console.log(state.isSyncTime);
      if (state.isSyncTime) {
        clearInterval(state.setTimer);

        state.formData.tab2.setUpTime = "";
      } else {
        const now = new Date();
        state.formData.tab2.setUpTime = now.toLocaleString();
        state.setTimer = setInterval(() => {
          const now = new Date();
          state.formData.tab2.setUpTime = now.toLocaleString();
        }, 1000);
      }
    };

    //重启系统
    const reStart = () => {
      restartSystem().then(
        (info) => {
          if (info.code === 200) {
            ElMessage({
              message: "重启成功",
              type: "success",
              offset: 400,
            });
          } else {
            ElMessage({
              message: info.message,
              type: "warning",
            });
          }
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };

    //恢复默认参数
    const resetConfigList = () => {
      resetConfig().then(
        (info) => {
          if (info.code === 200) {
            ElMessage({
              message: "恢复成功",
              type: "success",
              offset: 400,
            });
            getConfig();
          } else {
            ElMessage({
              message: info.message,
              type: "warning",
            });
          }
        },
        (err) => {
          ElMessage({
            message: err.message,
            type: "warning",
          });
        }
      );
    };

    const reStartA = () => {
      state.isShow = false;
      reStart();
    };

    return {
      ...toRefs(state),
      getConfig,
      handleTabCurrentChange,
      changeNowTime,
      resetConfigList,
      saveBasic,
      saveTime,
      changeWay,
      reStart,
      reStartA,
    };
  },
});
</script>

<template>
  <div class="system-container">
    <tab-card
      :tabs="['基本信息', '时间配置', '系统维护', '用户管理']"
      :default-index="defaultIndexNum"
      @changeIndex="handleTabCurrentChange"
    >
      <template v-if="currentTab === 0">
        <config-item title="设备名称">
          <config-input v-model:value="formData.tab1.deviceName" />
        </config-item>
        <config-item title="设备编号">
          <config-input v-model:value="formData.tab1.deviceNum" />
        </config-item>
        <config-item title="设备型号">
          <config-input disabled v-model:value="formData.tab1.deviceCategory" />
        </config-item>
        <config-item title="设备序列号">
          <config-input disabled v-model:value="formData.tab1.deviceSn" />
        </config-item>
        <save-button @click="saveBasic" />
      </template>
      <template v-if="currentTab === 1">
        <config-item title="时区" style="margin-left: 15px">
          <time-zone-select
            :width="530"
            v-model:value="formData.tab2.timezone"
          />
        </config-item>
        <module-card title="NTP校时">
          <el-checkbox
            @change="changeWay(0)"
            v-model="checkWay1"
            label="NTP校时"
          />
          <config-item title="服务器地址">
            <el-input
              v-model="formData.tab2.serveAddress"
              style="width: 340px"
              :disabled="!checkWay1"
            />
          </config-item>
          <config-item title="NTP端口">
            <el-input
              :disabled="!checkWay1"
              v-model="formData.tab2.ntpPort"
              style="width: 340px"
            />
          </config-item>
          <config-item title="校时时间间隔">
            <el-input
              :disabled="!checkWay1"
              v-model="formData.tab2.timingInterval"
              style="width: 340px"
            />分钟
          </config-item>
          <!-- <div class="test">测试</div> -->
        </module-card>
        <module-card title="手动校时">
          <el-checkbox
            @change="changeWay(1)"
            v-model="checkWay2"
            label="手动校时"
          />
          <config-item title="设备时间">
            <el-input
              disabled
              v-model="formData.tab2.deviceTime"
              style="width: 340px"
            />
          </config-item>
          <config-item title="设置时间">
            <el-date-picker
              class="setTime"
              v-model="formData.tab2.setUpTime"
              type="datetime"
            />
            <el-checkbox
              v-model="isSyncTime"
              @click="changeNowTime"
              label="与计算机时间同步"
            />
          </config-item>
        </module-card>
        <save-button @click="saveTime" />
      </template>
      <template v-if="currentTab === 2">
        <module-card title="重启">
          <config-item :has-title="false">
            <template #title>
              <!-- <info-button @click="reStart" title="重启" /> -->
              <button @click="reStart" class="cbtn">重启</button>
            </template>
            <span>重新启动设备</span>
          </config-item>
        </module-card>
        <module-card title="恢复默认值">
          <config-item :has-title="false">
            <template #title>
              <!-- <info-button @click="resetConfigList" title="完全恢复" /> -->
              <button @click="resetConfigList" class="cbtn">完全恢复</button>
            </template>

            <span>完全恢复设备参数到出厂设置</span>
          </config-item>
        </module-card>
      </template>
      <template v-if="currentTab === 3">
        <user-table style="margin-left: 15px" />
      </template>
    </tab-card>

    <el-dialog v-model="isShow" title="重启" width="500">
      <span>修改重启生效，是否立即重启</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShow = false">取消</el-button>
          <el-button type="primary" @click="reStartA"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.system-container {
  height: 100%;

  .test {
    width: 60px;
    height: 24px;
    text-align: center;
    line-height: 22px;
    margin-left: 150px;
    border: 1px solid black;
  }

  .setTime {
    width: 296px;
    input {
      width: 296px;
    }
    margin-right: 50px;
  }

  .cbtn {
    height: 26px;
    width: 100px;
    border: 1px solid #a3a3a3;
    display: inline-block;
    cursor: pointer;
    font-size: 14px;
    background-color: #f2f2f2;
  }
}
</style>
